package site.assad.service;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import site.assad.dao.UserDao;
import site.assad.domain.User;

/**
 * Author: Al-assad 余林颖
 * E-mail: yulinying_1994@outlook.com
 * Date: 2017/12/15 11:37
 * Description: 使用基于aop/tx 进行 xml 事务增强配置
 */
@Service
@Transactional
public class UserService {

    @Autowired
    private UserDao userDao;
    private final static Logger log = LogManager.getLogger();

    //标记方式使用缓存，当调用该方法时，会先从 users 缓存中匹配查询缓存对象，如果匹配则直接返回缓存对象，否则执行方法内的逻辑
    //在这个方法中，对应浑春的 key 为 userId 的值，value 为 userId 对应的 User 对象；
    @Cacheable(cacheNames = "users")
    public User getUser(final int userid){
        log.debug("real query user from DB");
        //不考虑缓存逻辑，直接实现业务
        User user = null;
        user = userDao.getUserById(userid);
        return user;
    }

    //将 userId 对应的 User 从缓存中删除
    @CacheEvict(cacheNames = "users",key="#userId")
    public void removeUserFromCache(int userId){
        log.debug("remove user "+ userId + " from cache");
    }



}
